package com.millstein.baier.handler;

import com.millstein.baier.exception.CustomerException;
import com.millstein.baier.model.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 统一异常处理类
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(CustomerException.class)
    public Result dealWithCustomerException(CustomerException e) {
        log.error("发生异常：{}", e.getMessage(), e);
        return Result.failure(e.getCode(), e.getMessage());
    }

    /**
     * 处理校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result dealWithValidException(MethodArgumentNotValidException e) {
        log.error("内容校验失败：{}", e.getMessage(), e);
        StringBuilder sb = new StringBuilder();
        for (ObjectError error : e.getBindingResult().getAllErrors()) {
            sb.append(error.getDefaultMessage()).append(" ");
        }
        return Result.failure("校验失败");
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    public Result dealWithOtherException(Exception e) {
        log.error("发生异常：{}", e.getMessage(), e);
        return Result.failure("服务器内部错误");
    }
}

